package edu.gatech.gro.model.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListGroup;

public class ListGroupItemJsonHandler extends JsonHandler {

	private static final String TAG = "LIST_GROUP_ITEM_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		List<ListGroup> dataParsed = new ArrayList<ListGroup>();
		try {
			JSONArray array = json.getJSONArray("data");
			for (int i = 0; i < array.length(); i++) {
				dataParsed.add(getListGroup(array.getJSONObject(i)));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	@Override
	protected void parseData() {
		ListGroup dataParsed = null;
		try {
			dataParsed = getListGroup(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public ListGroup getListGroup(JSONObject obj) {
		ListGroup group = new ListGroup();
		try {
			group.setId(obj.getInt("id"));
			group.setName(obj.getString("name"));
			group.setNameClean(obj.getString("nameClean"));
			if (obj.has("items") && obj.optJSONArray("items") != null) {
				JSONArray jsonItems = obj.getJSONArray("items");
				ArrayList<Item> list = new ArrayList<Item>();
				ItemJsonHandler h = new ItemJsonHandler();
				for (int i = 0; i < jsonItems.length(); i++) {
					list.add(h.getItem(jsonItems.getJSONObject(i)));
				}
				group.setItems(list);
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return group;
	}
}
